﻿using Microsoft.EntityFrameworkCore;
using Rbac.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Rbac.Repository
{
    /// <summary>
    /// 仓储基类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        protected RbacDbContext db;

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="admin"></param>
        /// <returns></returns>
        public int Create(T admin)
        {
            db.Set<T>().Add(admin);

            return db.SaveChanges();
        }

        /// <summary>
        /// 批量添加
        /// </summary>
        /// <param name="admin"></param>
        /// <returns></returns>
        public int Create(List<T> entitys)
        {
            db.Set<T>().AddRange(entitys);
            return db.SaveChanges();
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="admin"></param>
        /// <returns></returns>
        public int Update(T admin)
        {
            db.Set<T>().Update(admin);
            return db.SaveChanges();
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="admin"></param>
        /// <returns></returns>
        public int Delete(T admin)
        {
            db.Entry<T>(admin).State = EntityState.Deleted;
            return db.SaveChanges();
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public int Delete(int Id)
        {
            db.Set<T>().Remove(db.Set<T>().Find(Id));
            return db.SaveChanges();
        }

        public int ManyDelete(List<T> admins)
        {
            db.Set<T>().RemoveRange(admins);
            return db.SaveChanges();
        }

        public T Query(int AdminId)
        {
            return db.Set<T>().Find(AdminId);
        }

        public List<T> QueryAll()
        {
            return db.Set<T>().ToList();
        }

        public IQueryable<T> Query()
        {
            return db.Set<T>().AsQueryable();
        }
    }
}
